package com.zhoug.map2;

import org.osmdroid.util.GeoPoint;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zhoug
 * @Date: 2025-01-06
 * @Description:
 */
public class OsmdroidUtils {

    /**
     * 边界对象AreaBoundary转化成 List<List<GeoPoint>>
     *
     * @param areaBoundary
     * @return
     */
    public static List<List<GeoPoint>> areaBoundaryToGeoPoints(AreaBoundary areaBoundary) {
        if (areaBoundary == null) return null;
        List<List<GeoPoint>> points = null;
        List<List<List<Double>>> boundary = areaBoundary.getBoundary();
        if (boundary != null && !boundary.isEmpty()) {
            points = new ArrayList<>();
            for (int i = 0; i < boundary.size(); i++) {
                List<GeoPoint> b1 = null;
                List<List<Double>> lists = boundary.get(i);
                if (lists != null && !lists.isEmpty()) {
                    for (int j = 0; j < lists.size(); j++) {
                        List<Double> doubles = lists.get(j);
                        if (doubles != null && doubles.size() == 2) {
                            if (b1 == null) {
                                b1 = new ArrayList<>();
                                points.add(b1);
                            }
                            b1.add(new GeoPoint(doubles.get(1), doubles.get(0)));
                        }
                    }
                }
            }
        }
        return points == null || points.isEmpty() ? null : points;
    }

    /**
     * 计算集合中点的边界点
     * @param list
     * @return
     */
    public static MapBound computeBounds(List<GeoPoint> list) {
        double minLatitude = Double.MAX_VALUE;
        double maxLatitude = Double.MIN_VALUE;
        double minLongitude = Double.MAX_VALUE;
        double maxLongitude = Double.MIN_VALUE;

        if (list != null && !list.isEmpty()) {
            for (GeoPoint geoPoint : list) {
                double latitude = geoPoint.getLatitude();
                double longitude = geoPoint.getLongitude();
                if (latitude < minLatitude) {
                    minLatitude = latitude;
                }
                if (latitude > maxLatitude) {
                    maxLatitude = latitude;
                }
                if (longitude < minLongitude) {
                    minLongitude = longitude;
                }
                if (longitude > maxLongitude) {
                    maxLongitude = longitude;
                }
            }

        }
        if (minLatitude != Double.MAX_VALUE && maxLatitude != Double.MIN_VALUE &&
                minLongitude != Double.MAX_VALUE && maxLongitude != Double.MIN_VALUE) {
            return new MapBound(minLatitude, minLongitude, maxLatitude, maxLongitude);
        }
        return null;
    }

}
